﻿using System;
using System.Linq;
using dIRca.Extras;
#if (WINDOWS_PHONE)
using Microsoft.Phone.Reactive;
#else
#endif

namespace dIRca.Network
{
    public class NetworkMonitor : IDisposable
    {
        private readonly INetworkService _networkService;
        private IDisposable _statusObserver;

        public bool IsStarted { get; private set; }
        public bool IsUp { get; private set; }

        public event EventHandler NetworkUp;
        public event EventHandler NetworkDown;

        public NetworkMonitor()
        {
            _networkService = new Extras.NetworkMonitor(10000);
            IsStarted = false;
        }

        public void Start()
        {
            if (_statusObserver != null)
                return;

            _statusObserver = _networkService.Status()
                .ObserveOnDispatcher()
                .Subscribe(type =>
                {
                    ProcessEvent(type);
                });

            IsStarted = true;
        }

        public void Stop()
        {
            if (_statusObserver == null)
                return;

            _statusObserver.Dispose();
            _statusObserver = null;
            IsStarted = false;
        }

        void ProcessEvent(bool status)
        {
            if (status)
            {
                if (!IsUp)
                {
                    IsUp = true;
                    OnNetworkUp();
                }
            }
            else
            {
                if (IsUp)
                {
                    IsUp = false;
                    OnNetworkDown();
                }
            }
        }

        void OnNetworkUp()
        {
            var handler = NetworkUp;
            if (handler != null)
                handler(this, new EventArgs());
        }

        void OnNetworkDown()
        {
            var handler = NetworkDown;
            if (handler != null)
                handler(this, new EventArgs());
        }

        public void Dispose()
        {
            Stop();
        }
    }
}